package com.entities.projectteam.list;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;

import com.core.managers.SessionFactoryManager;
import com.core.protocols.ICustomDatasourceDelegate;
import com.core.protocols.IServiceLayerDelegate;
import com.core.protocols.ITableViewDatasource;
import com.core.protocols.ITableViewDelegate;
import com.core.ui.controller.base.CustomController;
import com.core.ui.customcell.TableViewCell;
import com.core.ui.customcell.TableViewDataCell;
import com.core.ui.customview.TableViewHeaderCell;
import com.core.utils.GlobalConstants;
import com.core.utils.HTMLTagUtils;
import com.core.utils.IndexPath;
import com.core.utils.LocalizableString;
import com.entities.projectitem.servicelayer.ProjectListLayer;
import com.entities.projectteam.servicelayer.TeamMemberListLayer;
import com.model.KeyValue;
import com.model.project.ProjectItem;
import com.model.project.TeamMember;
import com.model.user.User;


public class TeamMemberListController
        extends CustomController
        implements ITableViewDatasource, ITableViewDelegate, IServiceLayerDelegate {

	ArrayList <TeamMember>            projectTeamList      = null;

	TeamMemberListLayer              projectTeamListLayer = null;
	ProjectListLayer                  projectListLayer     = null;

	private String                    projectId            = null;
	private ICustomDatasourceDelegate delegate             = null;



	public String getProjectId () {

		return projectId;
	}



	public void setProjectId ( String projectId ) {

		this.projectId = projectId;
	}



	@Override
	public void setCustomDatasourceDelegate ( ICustomDatasourceDelegate delegate ) {

		this.delegate = delegate;

	}



	@Override
	public void reloadData () {

		Integer id = null;
		try {
			id = Integer.parseInt(projectId);
		} catch ( NumberFormatException e ) {
			id = null;
		}

		if ( id == null ) {
			return;
		}

		projectListLayer = new ProjectListLayer();
		projectListLayer.objectByUNID(id, null, this);

	}



	@Override
	public <T> void responseResponseItemsList ( List <T> items,
	                                            Object request,
	                                            Exception exception ) {

		projectTeamList = new ArrayList <TeamMember>();

		if ( exception != null ) {
			return;
		}

		if ( items == null ) {
			return;
		}


		Session session = SessionFactoryManager.sharedInstance().openSession();
		try {

			ProjectListLayer layer = new ProjectListLayer();
			for ( T item : items ) {
				Integer id = ((ProjectItem) item).getId();
				ProjectItem projectItem = (ProjectItem) layer.objectByUNID(id, session, null);
				if ( projectItem == null ) {
					continue;
				}

				Set <TeamMember> projectMembers = null;
				try {
					projectMembers = projectItem.getProjectTeam();
				} catch ( Exception e ) {
					e.printStackTrace();
				} finally {

				}

				if ( projectMembers == null ) {
					continue;
				}

				for ( TeamMember member : projectMembers ) {
					projectTeamList.add(member);
				}

			}
		} finally {
			session.close();
		}

		if ( this.delegate != null ) {
			this.delegate.refreshContent();
		}

	}



	@Override
	public String tableStyleClassName () {

		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public String headerRowStyleClassNameAtIndex ( int index ) {

		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public String headerCellStyleClassNameAtIndexPath ( IndexPath indexPath ) {

		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public String cellStyleClassNameAtIndexPath ( IndexPath indexPath ) {

		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public String rowStyleClassNameAtIndex ( int index ) {

		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public int numberOfHeadRows () {

		// TODO Auto-generated method stub
		return 1;
	}



	@Override
	public int numberOfHeadCols () {

		// TODO Auto-generated method stub
		return 3;
	}



	@Override
	public TableViewHeaderCell headCellAtIndexPath ( IndexPath indexPath ) {

		LocalizableString localizableString = LocalizableString.sharedInstance();

		TableViewHeaderCell result = new TableViewHeaderCell();
		result.setStyleName("headerCellSimple");
		switch ( indexPath.getCol() ) {
			case 0: {
				result.setText("#");
				break;
			}
			case 1: {
				result.setText(localizableString.localizable("entity.ProjectTask.field.name"));
				break;
			}
			case 2: {
				result.setText(localizableString.localizable("grid.column.operation"));
				break;
			}

			default:
				break;
		}
		return result;
	}



	@Override
	public int numberOfDataRows () {

		if ( projectTeamList == null ) {
			return 0;
		} else {
			return projectTeamList.size();
		}
	}



	@Override
	public int numberOfDataCols () {

		// TODO Auto-generated method stub
		return 3;
	}



	@Override
	public TableViewCell dataCellAtIndexPath ( IndexPath indexPath ) {

		LocalizableString localizableString = LocalizableString.sharedInstance();

		TeamMember member = projectTeamList.get(indexPath.getRow());
		TableViewDataCell result = new TableViewDataCell();
		String idValue = member.idValue().toString();
		String idStrValue = member.idValue().getValue();


		switch ( indexPath.getCol() ) {
			case 0: {
				result.setStyleName("dataCellSimple");
				result.setText(String.format("%d", 1 + indexPath.getRow()));
				break;
			}
			case 1: {
				String userName = "n/a";
				if ( member != null ) {
					User user = member.getTeamMemberCategory().getUser();
					if ( user != null ) {
						userName = user.getName();
					}
				}
				result.setStyleName("dataCellSimple maxwidth");
				result.setText(userName);
				result.setOnCellClick("%s?%s", GlobalConstants.SERVLET_TEAMMEMBERINFO, idValue);
				break;
			}
			case 2: {
				result.setStyleName("dataCellSimple");
				String link = String.format("%s?%s", GlobalConstants.SERVLET_TEAMMEMBERUPDATE, idValue);
				ArrayList <KeyValue> attrs = new ArrayList <KeyValue>();
				attrs.add(new KeyValue("href", link, true));
				attrs.add(new KeyValue("class", "trigger_lnk", true));
				String editText = HTMLTagUtils.customTag("a", attrs, localizableString.localizable("object.operation.edit"));

				String ajax = String.format("javascript:deleteTeamMember(%s);", idStrValue);
				link = "javascript:void(0);";

				attrs = new ArrayList <KeyValue>();
				attrs.add(new KeyValue("href", link, true));
				attrs.add(new KeyValue("class", "trigger_lnk", true));
				attrs.add(new KeyValue("onclick", ajax, true));
				String deleteText = HTMLTagUtils.customTag("a", attrs, localizableString.localizable("object.operation.delete"));

				result.setText(String.format("%s|%s", editText, deleteText));
				break;

			}
			default: {
				break;
			}
		}
		return result;
	}
}
